<template>
  <div class="u-page mai-conversation-add">
	  <!-- 自定义发圈 头部  开始 -->
	  <div class="my_top_head_and_msg margin-bottom-10">
		<div @click="UpdateAvatarShow(true)" class="head_avatar"><img :src="userProfile.avatar || 'https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png'"  /></div>
		<div class="head_msg">
			<div class="username_and_qrcode">
				<div @click="UpdateNickShow(true)" class="head_username">{{ userProfile.nick || "---设置昵称--" }}</div>
				<div class="head_qrcode"><img src="/static/icon/my/qrcode.png"  /></div>
			</div>
			<div class="wechat_id_and_arrow">
				<div class="wechat_userId">用户ID:{{ userProfile.userID }}</div>
				<!-- <div class="user_arrow_right"><u-icon style="margin-top: 10px;" name="arrow-right" color="#ddd" size="20"></u-icon></div> -->
			</div>
			<div class="wechat_id_and_arrow">
				<div class="wechat_userId">邀请码:{{ invitationCode }}</div>
				<!-- <div class="user_arrow_right"><u-icon style="margin-top: 10px;" name="arrow-right" color="#ddd" size="20"></u-icon></div> -->
			</div>
			<div class="user_status_and_update">
				<div class="user_status">+状态</div>
				<div class="user_status_update"><u-icon style="margin-top: 6px;" name="reload" color="#aaa" size="24"></u-icon></div>
			</div>
		</div>
	  </div>
	  <!-- 自定义发圈 头部  结束 -->
	  
	  <!-- 背景图 名称 头像  开始 -->
	  <div class="bg_list_show">
		  <!-- 朋友圈 -->
		  <div class="show_item margin-bottom-10">
			  <div class="show_item_icon"><img src="/static/icon/my/fuwu.png"></div>
			  <div class="show_item_text">支付与服务</div>
			  <div class="show_itme_arrow"><u-icon name="arrow-right" color="#ddd" size="22"></u-icon></div>
		  </div>
		  
		  <!-- 收藏 -->
		  <div class="show_item margin-bottom-1">
		  	<div class="show_item_icon"><img src="/static/icon/my/shoucang.png"></div>
		  	<div class="show_item_text">收藏</div>
		  	<div class="show_itme_arrow"><u-icon name="arrow-right" color="#ddd" size="22"></u-icon></div>
		  </div>
		  
		  <!-- 朋友圈 -->
		  <div @click="goMoments()" class="show_item margin-bottom-1">
		  	<div class="show_item_icon"><img src="/static/icon/my/pengyouquan.png"></div>
		  	<div class="show_item_text">朋友圈</div>
		  	<div class="show_itme_arrow"><u-icon name="arrow-right" color="#ddd" size="22"></u-icon></div>
		  </div>
		  
		  <!-- 表情 -->
		  <div class="show_item margin-bottom-10">
		  	<div class="show_item_icon"><img src="/static/icon/my/biaoqing.png"></div>
		  	<div class="show_item_text">表情</div>
		  	<div class="show_itme_arrow"><u-icon name="arrow-right" color="#ddd" size="22"></u-icon></div>
		  </div>
		  
		  <!-- 设置 -->
		  <div @click="goSet()" class="show_item margin-bottom-10">
		  	<div class="show_item_icon"><img src="/static/icon/my/shezhi.png"></div>
		  	<div class="show_item_text">设置</div>
		  	<div class="show_itme_arrow"><u-icon name="arrow-right" color="#ddd" size="22"></u-icon></div>
		  </div>
		  

	  </div>
	  <!-- 背景图 名称 头像  结束 -->
	  
	  <!-- 更新昵称 -->
	  <u-overlay :show="isShowNickDialog" @click="isShowNickDialog = false" :duration="400" :z-index ="999" :opacity="0">
		  <Dialog
		    :show="true"
			@submit="submitNick"
			@update:show="close"
		  >
			<input v-model="nick" focus placeholder="请输入昵称" />
		  </Dialog>
	  </u-overlay>
	  
	  <!-- 更新头像 -->
	  <u-overlay :show="isShowAvatarDialog" @click="isShowAvatarDialog = false" :duration="400" :z-index ="999" :opacity="0">
		  <Dialog
		   :show="true"
			@submit="submitAvatar"
			@update:show="close"
		  >
			<uni-file-picker 
				v-model="avatarImg"  
				file-mediatype="image"
				mode="grid"
				file-extname="png,jpg"
				:limit="1"
				@progress="progress" 
				@success="success" 
				@fail="fail" 
				@select="select"
			/>
		  </Dialog>
	  </u-overlay>	  

	  
  </div>
</template>
<script lang="ts" setup>
import TUIChatEngine, {
  TUIUserService,
  TUIStore,
  StoreName,
  TUIChatService,
} from '@tencentcloud/chat-uikit-engine';
import { TUITranslateService } from '@tencentcloud/chat-uikit-engine';
import { TUILogin } from '@tencentcloud/tui-core';
import { TUIGlobal } from '@tencentcloud/universal-api';
import { ref, defineProps, onMounted } from '/TUIKit/adapter-vue';
import { isPC } from '/TUIKit/utils/env';
import { Toast, TOAST_TYPE } from '/pages/common/Toast/index';
import BottomPopup from '/pages/common/BottomPopup/index.vue';
import Dialog from '/pages/common/Dialog/index.vue';
import Icon from '/pages/common/Icon.vue';
import rightArrowIcon from '/TUIKit/assets/icon/right-icon.svg';
import { IUserProfile } from '/TUIKit/interface';
import { onHide } from '@dcloudio/uni-app';
import { translator } from '/pages/chat/utils/translation';
import { removeTokenStorage } from '/utils/token';

const props = defineProps({
  displayType: {
    type: String,
    default: 'all', // "profile"/"setting"/"all"
  },
  showSetting: {
    type: Boolean,
    default: false,
  },
});

// 编辑对话框
const isShowNickDialog = ref<boolean>(false);;
const nick = ref();

const invitationCode = uni.getStorageSync('invitationCode');
// 头像设置
const isShowAvatarDialog =ref<boolean>(false);;
const avatarImg = ref();
const avatarImgUrl = ref();

// 用户信息
const userProfile = ref<IUserProfile>({});


// 跳转到设置
const goSet = () =>{
	uni.navigateTo({
		url:'/pages/my/set'
	})
}


// 显示弹窗 昵称
const UpdateNickShow = (item: any) => {
	isShowNickDialog.value = true
};

// 显示弹窗 头像
const UpdateAvatarShow = (item: any) => {
	isShowAvatarDialog.value = true
};

// 编辑资料 确认操作
const submitNick = () => {
	isShowNickDialog.value = false
	if(nick.value != ''){
		// 1. 更新腾讯云昵称
		updateMyProfile({ nick: nick.value });

		// 2. 同步更新后端昵称
		updateNicknameToBackend(uni.getStorageSync("userAppInfo").id, nick.value);
	}
}

// 同步昵称到后端
const updateNicknameToBackend = (userID: string, nick: string) => {
  let base_url = uni.$baseUrl
  let token = uni.getStorageSync('token');

  uni.request({
    url: base_url + '/home/user/update_nickname_tencent',
    method: 'POST',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'X-Csrf-Token': token,
    },
    data: {
      user_id: userID,
      nickname: nick,
    },
    success: (res) => {
      const { code, msg } = res.data;
      if (code === 200) {
        Toast({
          message: '昵称已同步至后端',
          type: TOAST_TYPE.SUCCESS,
          duration: 2000,
        });
      } else {
        Toast({
          message: '后端昵称更新失败: ' + msg,
          type: TOAST_TYPE.ERROR,
          duration: 3000,
        });
      }
    },
    fail: (err) => {
      Toast({
        message: '请求失败: ' + JSON.stringify(err),
        type: TOAST_TYPE.ERROR,
        duration: 3000,
      });
    },
  });
};

// 更新头像
const submitAvatar = () => {
	isShowAvatarDialog.value = false
	if(avatarImgUrl.value != ''){
	  updateMyProfile({ avatar: avatarImgUrl.value });
	}
}

// 关闭弹窗
const close = () => {
	isShowNickDialog.value = false
	isShowAvatarDialog.value = false
}

// 自动文件上传 处理过程
const progress = (option) => {
	console.log(option)
}
// 自动文件上传 成功
const success = (option) => {
	console.log(option)
}
// 自动文件上传 失败
const fail = (option) => {
	console.log(option)
}
// 自动文件上传 选择
const select = (option) => {

	let base_url = uni.$baseUrl
	uni.uploadFile({
		url: base_url+'/home/user/uploads', // 仅为示例，非真实的接口地址
		filePath: option.tempFilePaths[0],
		name: 'file',
		header:{
			"X-Csrf-Token":uni.getStorageSync('token')
		},
		formData: {
			// user: 'test'
		},
		success: (res) => {
			let data = JSON.parse(res.data)
			avatarImgUrl.value = base_url+data.data

			// ✅ 更新腾讯资料
			updateMyProfile({ avatar: avatarImgUrl.value });

			// ✅ 同步更新到你自己的后端数据库
			// 注意：接口路径、字段名请根据你的后端接口文档自行修改
			uni.request({
				url: base_url + '/home/user/update_avatar', // 示例：你的后端接口地址
				method: 'POST',
				header: {
					"Content-Type": "application/json",
					"X-Csrf-Token": uni.getStorageSync('token')
				},
				data: {
					user_id:uni.getStorageSync("userAppInfo").id,
					avatar: avatarImgUrl.value
				},
				success: (res) => {
					if (res.data.code == 200) {
						uni.showToast({ title: '头像已同步更新', icon: 'success' });
					} else {
						uni.showToast({ title: '头像同步失败', icon: 'none' });
					}
				},
				fail: (err) => {
					console.error('更新本地后端失败:', err);
					uni.showToast({ title: '请求失败', icon: 'none' });
				}
			});
		}
	});
}

// 自定义 更新用户资料 函数 利用接口实现
const updateMyProfile = (props: object) => {
  TUIUserService.updateMyProfile(props)
    .then((res: any) => {
      Toast({
        message: '更新用户资料成功',
        type: TOAST_TYPE.SUCCESS,
        duration: 0,
      });
    })
    .catch((err: any) => {
      console.warn('更新用户资料失败', err);
      Toast({
        message: '更新用户资料失败',
        type: TOAST_TYPE.ERROR,
        duration: 0,
      });
    });
};

// 去朋友圈
const goMoments = () =>{
	uni.navigateTo({
		url:'/pages/moments/index'
	})
}

// 监控用户资料编辑
TUIStore.watch(StoreName.USER, {
  // 显示用户基本信息
  userProfile: (userProfileData: IUserProfile) => {
	userProfile.value = { ...userProfile.value, ...userProfileData }; // ✅ 强制触发更新
  },
});

// 规避TUIStore.watch userProfile 登录后暂时不能及时触发更新
onMounted(() => {
  TUIUserService.getUserProfile()
    .then((res: any) => {
      userProfile.value = res.data;
    })
    .catch(() => {
      console.warn('用户未登录，无法获取资料');
    });
});



</script>

<style>
	.margin-bottom-10{
		margin-bottom: 10px;
	}
	.margin-bottom-1{
		margin-bottom: 1px;
	}
	.mai-conversation-add{
		width: 100%; 
		height: 100%;
		display: flex;
		background-color: #fff;
		overflow: hidden;
		flex-direction: column;
		background-color: #f5f5f5;
	}
	/* 用户头部 */
	.my_top_head_and_msg{
		display: flex;
		background-color: #fff;
		padding-top: 40px;
		height: 170px;
	}
	.head_avatar{
		width: 120px;
		justify-content: center;
	}
	.head_avatar img{ width: 80px; height: 80px; margin-left: 20px; margin-top: 20px;}
	.head_msg{
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;		
	}
	.username_and_qrcode{
		width: 100%;
		display: flex;
		height: 40px;
		line-height: 40px;
	}
	.head_username{
		font-weight: bold;
		font-size: 32rpx;
		color: blue;
		flex: 1;
	}
	.head_qrcode{
		width: 22px;
		height: 22px;
		margin-right: 20px;
	}
	.head_qrcode img{width: 100%; height: 100%;}
	.wechat_id_and_arrow{
		width: 100%;
		display: flex;
		height: 40px;
		line-height: 40px;
	}
	.wechat_userId{
		flex: 1;
		height: 40px;
		line-height: 40px;
	}
	.user_arrow_right{
		height: 40px;
		line-height: 40px;
		width: 40px;
		align-items: center;
	}
	.user_status_and_update{
		margin-top: 6px;
		width: 100%;
		display: flex;
		height: 40px;
		line-height: 40px;
	}
	.user_status{
		width: 80px;
		height: 30px;
		line-height: 30px;
		border-radius: 20px;
		background-color: #eee;
		border: 1px solid #ddd;
		text-align: center;
		color: #666;
	}
	.user_status_update{
		margin-left: 8px;
	}

	/* 朋友圈背景图 姓名 头像 */
	.bg_list_show{
		width: 100%;
		display: flex;
		flex-direction: column;
	}
	.show_item{
		display: flex;
		height: 60px;
		background-color: #fff;
		align-items: center;
	}
	.show_item_icon{width: 40px; margin-left: 10px; margin-top: 8px;}
	.show_item_icon img{width: 30px; height: 30px;}
	.show_item_text{
		height: 60px;
		line-height: 60px;
		flex: 1;
	}
	.show_itme_arrow{
		margin-right: 10px;
	}
	

</style>
